package com.mini.cn.goods.io.netty.io;



import io.netty.util.internal.PlatformDependent;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Created with IntelliJ IDEA.
 * User: fly
 * Date: 2020-07-16
 * Time: 9:51 上午
 */
public class MonitorUtils {
    /**
     * 通过反射方式获取类实例变量的值
     *
     * @param cls
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Class cls, String fieldName) {
        Field[] fields = cls.getDeclaredFields();
        try {
            for (Field field : fields) {
                // 下面这行在fortify扫描时会报 Access Specifier Manipulation，按建议要换成ReflectionUtils.makeAccessible(field);
                field.setAccessible(true);
                if (fieldName.equalsIgnoreCase(field.getName()) && Modifier.isStatic(field.getModifiers())) {
                    return field.get(cls);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取Netty的直接内存计数值
     *
     * @return
     */
    public static Object getNettyDirectMemoryCounter() {
        return getFieldValue(PlatformDependent.class, "DIRECT_MEMORY_COUNTER");
    }

    /**
     * 获取Netty的直接内存最大值
     *
     * @return
     */
    public static Object getNettyDirectMemoryLimit() {
        return getFieldValue(PlatformDependent.class, "DIRECT_MEMORY_LIMIT");
    }

}
